package com.song.Niodemo01.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class TestServer {

	private  Selector selector=null;
	
	public void init()
	{
		try {
			selector = Selector.open();
			ServerSocketChannel server = ServerSocketChannel.open();
			server.socket().bind(new InetSocketAddress(9999));
			server.configureBlocking(false);
			server.register(selector, SelectionKey.OP_ACCEPT);
			while(selector.select()>0)
			{
				for(SelectionKey sk : selector.selectedKeys())
				{
					selector.selectedKeys().remove(sk);
					if(sk.isAcceptable())
					{
						SocketChannel sc = server.accept();
						sc.configureBlocking(false);
						sc.register(selector, SelectionKey.OP_READ);
					}
					if(sk.isReadable())
					{
						SocketChannel sc = (SocketChannel)sk.channel();
						ByteBuffer bb = ByteBuffer.allocate(1024);
						String content ="";
						
						while(sc.read(bb)>0)
						{
							bb.flip();
							content += StandardCharsets.UTF_8.decode(bb);
						}
						System.out.println("      =====   "+content);
						if(content.length()>0)
						{
							for(SelectionKey key :selector.keys())
							{
								Channel targetChannel = key.channel();
								if(targetChannel instanceof SocketChannel)
								{
									SocketChannel dest =(SocketChannel)targetChannel;
									dest.write(StandardCharsets.UTF_8.encode(content+"  hahah "));
								}
							}
						}
						
					}
				}
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	
	
	public static void main(String[] args) {
		new TestServer().init();
	}
}
